package com.zdkj.subway.st.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.exceltools.ExcelUtil;
import com.zdkj.common.core.exceltools.IExcelExport;
import com.zdkj.common.core.exceltools.IExcelParser;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.dto.in.SwstInputDetailDTO;
import com.zdkj.subway.st.dto.in.SwstOutputDetailDTO;
import com.zdkj.subway.st.entity.SwStInputDetail;
import com.zdkj.subway.st.entity.SwStOutputDetail;
import com.zdkj.subway.st.entity.SwTkStockFlow;
import com.zdkj.subway.st.service.SwTkStockFlowService;
import com.zdkj.subway.st.service.impl.SwStInputDetailServiceImpl;
import com.zdkj.subway.st.service.impl.SwStOutputDetailServiceImpl;
import com.zdkj.subway.st.util.DateUtilsSt;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @ProjectName: zdkj
 * @Package: com.zdkj.subway.st.controller
 * @ClassName: SwTkStockFlowController
 * @Description:
 * @Author: kangjian
 * @CreateDate: 2020/8/9 12:31
 * @Version: 1.0
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swTkStockFlow")
@Api(value = "swTkStockFlow", tags = "库内流动")
public class SwTkStockFlowController {

    private final SwTkStockFlowService swTkStockFlowService;

    @Resource
    SwStOutputDetailServiceImpl outputDetailServiceImpl;

    @Resource
    SwStInputDetailServiceImpl inputDetailServiceImpl;

    private final SwStOutputDetailServiceImpl swStOutputDetailService;

    private final SwStOutputDetailController swStOutputDetailController;
    private final SwStInputDetailController swStInputDetailController;

    private final SwStInputDetailServiceImpl swStInputDetailService;

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(swTkStockFlowService.getById(id));
    }

    @GetMapping("/page")
    public R<IPage> getDictPage(Page page, SwTkStockFlow swTkStockFlow, String applyTimeDTO) {
        return R.ok(swTkStockFlowService.page(page, Wrappers.query(swTkStockFlow).orderByDesc("apply_time").lambda()
                .likeRight(applyTimeDTO != null, SwTkStockFlow::getApplyTime, applyTimeDTO)
                .eq(swTkStockFlow.getFlowBeforeTicketArea() != null, SwTkStockFlow::getFlowBeforeTicketArea, swTkStockFlow.getFlowBeforeTicketArea())
        ));
    }

    @SysLog("库内流动保存信息")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_stock_flow_add')")
    public R save(@Valid @RequestBody SwTkStockFlow swTkStockFlow) {
        PigxUser user = SecurityUtils.getUser();
        swTkStockFlow.setCreatorName(user.getUsername());
        swTkStockFlow.setCreatorId((long) user.getId());
        swTkStockFlow.setCheckStatus(CommonConstants.UN_SUBMIT);
        return R.ok(swTkStockFlowService.save(swTkStockFlow));
    }

    @PostMapping("/inner")
    @Inner
    public R feignSave(@Valid @RequestBody SwTkStockFlow swTkStockFlow) {
        swTkStockFlow.setCheckStatus(CommonConstants.UN_SUBMIT);
        return R.ok(swTkStockFlowService.save(swTkStockFlow));
    }


    @SysLog("删除库内流动信息")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_stock_flow_delete')")
    public R removeById(@PathVariable String id) {
        return R.ok(swTkStockFlowService.removeById(id));
    }


    @ApiOperation(value = "批量删除库内流动信息", notes = "批量删除库内流动信息")
    @SysLog("批量删除库内流动信息")
    @PostMapping("batchDelete")
    @PreAuthorize("@pms.hasPermission('st_stock_flow_delete')")
    public R batchDeleteById(@RequestBody List<Integer> idList) {
        List<Integer> deleteList = new ArrayList<>();
        idList.forEach(id -> {
            SwTkStockFlow swTkStockFlow = swTkStockFlowService.getById(id);
            //只有未提交的才能删除
            if (!CommonConstants.UN_SUBMIT.equals(swTkStockFlow.getCheckStatus())) {
                log.info("已提交/审核数据不能删除！");
            } else {
                deleteList.add(id);
            }
        });
        return R.ok(swTkStockFlowService.removeByIds(deleteList));
    }

    @ApiOperation(value = "批量提交库内流动信息", notes = "批量提交库内流动信息")
    @SysLog("批量提交库内流动信息")
    @PutMapping("/submit")
    public R submit(@RequestBody List<Integer> idList) {
        List<SwTkStockFlow> submitList = new ArrayList<>();
        idList.forEach(id -> {
            SwTkStockFlow submitItem = new SwTkStockFlow();
            submitItem.setId(id);
            submitItem.setCheckStatus(CommonConstants.SUBMIT);
            submitList.add(submitItem);
        });
        return R.ok(swTkStockFlowService.updateBatchById(submitList));
    }

    @PutMapping
    @SysLog("修改库内流动信息")
    @PreAuthorize("@pms.hasPermission('st_stock_flow_update')")
    public R updateById(@Valid @RequestBody SwTkStockFlow swTkStockFlow) {
        PigxUser user = SecurityUtils.getUser();
        swTkStockFlow.setCreatorName(user.getUsername());
        swTkStockFlow.setCreatorId((long) user.getId());
        return R.ok(swTkStockFlowService.updateById(swTkStockFlow));
    }

    @PutMapping("/audit")
    @SysLog("审核库内流动信息")
    public R auditByIds(@RequestBody List<SwTkStockFlow> swTkStockFlowList) {
        if (swTkStockFlowList == null) {
            return R.failed();
        }
        SwTkStockFlow swTkStockFlow = swTkStockFlowList.get(0);
        if (!"2".equals(swTkStockFlow.getCheckStatus())) {
            return R.ok(swTkStockFlowService.updateBatchById(swTkStockFlowList));
        }
        //1.先更新状态
        swTkStockFlowService.updateBatchById(swTkStockFlowList);
        //2.审批通过 新增一条出库 实际做出库操作  ==》 新增一条入库 做入库操作
        List<SwStOutputDetail> list = new ArrayList<>();
        List<SwStInputDetail> inputDetails = new ArrayList<>();
        for (SwTkStockFlow stockFlow : swTkStockFlowList) {
            SwStOutputDetail swStOutputDetail = new SwStOutputDetail();
            swStOutputDetail.setOutGoingType("10");
            swStOutputDetail.setOutGoingTime(DateUtilsSt.newLocalDateTime());
            swStOutputDetail.setKeepercode(stockFlow.getApplyPersonCode());
            swStOutputDetail.setKeepername(stockFlow.getApplyPersonName());
            swStOutputDetail.setTicketType(stockFlow.getTicketType());
            swStOutputDetail.setTicketName(stockFlow.getTicketName());
            swStOutputDetail.setTicketTimes(stockFlow.getTicketTimes());
            swStOutputDetail.setTicketPrice(stockFlow.getTicketPrice());
            swStOutputDetail.setTicketNumber(stockFlow.getStorageNumber());
            swStOutputDetail.setActiveTime("0");
            swStOutputDetail.setTicketNo("");
            swStOutputDetail.setKeeper1code(stockFlow.getApplyPersonCode());
            swStOutputDetail.setKeeper1name(stockFlow.getApplyPersonName());
			if (StringUtils.isNotEmpty(swTkStockFlow.getFlowReason())) {
               swStOutputDetail.setRemark(swTkStockFlow.getFlowReason());
            }
            //swStOutputDetail.setRemark(stockFlow.getRemark());
            swStOutputDetail.setDataSource("0");
            //出库生成单号和更新基础表信息
            outputDetailServiceImpl.outputGenerateSingle(swStOutputDetail);
            list.add(swStOutputDetail);

            //入库数据
            SwStInputDetail swStInputDetail = new SwStInputDetail();
            swStInputDetail.setInGoingType("10");
            swStInputDetail.setInGoingTime(DateUtilsSt.newLocalDateTime());
            swStInputDetail.setKeepercode(stockFlow.getApplyPersonCode());
            swStInputDetail.setKeepername(stockFlow.getApplyPersonName());
            swStInputDetail.setTicketType(stockFlow.getTicketType());
            swStInputDetail.setTicketName(stockFlow.getTicketName());
            swStInputDetail.setTicketTimes(stockFlow.getTicketTimes());
            swStInputDetail.setTicketPrice(stockFlow.getTicketPrice());
            swStInputDetail.setTicketNumber(stockFlow.getStorageNumber());
            swStInputDetail.setActiveTime("0");
            swStInputDetail.setTicketNo("");
            swStInputDetail.setKeeper1code(stockFlow.getApplyPersonCode());
            swStInputDetail.setKeeper1name(stockFlow.getApplyPersonName());
            if (StringUtils.isNotEmpty(stockFlow.getFlowReason())) {
               swStInputDetail.setRemark(stockFlow.getFlowReason());
            }
            swStInputDetail.setDataSource("0");//数据来源：2：配送
            //入库生成单号和更新基础表信息
            inputDetailServiceImpl.inputGenerateSingle(swStInputDetail);
            inputDetails.add(swStInputDetail);
        }
        swStOutputDetailService.saveBatch(list);

        // 3.保存之后调用 实际出库操作  SwStOutputDetailController.putBatchObj
        SwstOutputDetailDTO swstOutputDetailDTO = new SwstOutputDetailDTO();
        List<Integer> idList = list.stream().map(SwStOutputDetail::getId).collect(Collectors.toList());
        swstOutputDetailDTO.setIds(idList);
        SwStOutputDetail swStOutputDetail = new SwStOutputDetail();
        swStOutputDetail.setKeeper2code(swTkStockFlow.getApplyPersonCode());
        swStOutputDetail.setKeeper2name(swTkStockFlow.getApplyPersonName());
        swStOutputDetail.setStockArea(swTkStockFlow.getFlowBeforeTicketArea());
        if (StringUtils.isNotEmpty(swTkStockFlow.getFlowReason())) {
            swStOutputDetail.setRemark(swTkStockFlow.getFlowReason());
        }
        swstOutputDetailDTO.setSwStOutputDetail(swStOutputDetail);
        swStOutputDetailController.putBatchObj(swstOutputDetailDTO);

        //4. 入库
        swStInputDetailService.saveBatch(inputDetails);
        // 5.调用入库操作
        SwstInputDetailDTO swstInputDetailDTO = new SwstInputDetailDTO();
        List<Integer> integerList = inputDetails.stream().map(SwStInputDetail::getId).collect(Collectors.toList());
        swstInputDetailDTO.setIds(integerList);
        SwStInputDetail swStInputDetail = new SwStInputDetail();
        swStInputDetail.setStockArea(swTkStockFlow.getFlowAfterTicketArea());
        swStInputDetail.setKeeper2code(swTkStockFlow.getApplyPersonCode());
        swStInputDetail.setKeeper2name(swTkStockFlow.getApplyPersonName());
        if (StringUtils.isNotEmpty(swTkStockFlow.getFlowReason())) {
            swStInputDetail.setRemark(swTkStockFlow.getFlowReason());
        }
        swstInputDetailDTO.setSwStInputDetail(swStInputDetail);
        swStInputDetailController.putBatchObj(swstInputDetailDTO);
        return R.ok();
    }

    @PostMapping(value = "/import")
    @SysLog("导入库内流动信息")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        try {
            File efile = MultipartFileToFile.multipartFileToFile(file);
            Workbook workbook = ExcelUtil.chooseWorkbook(efile);
            Sheet sheet = workbook.getSheetAt(0);
            IExcelParser excelParser = SpringContextHolder.getBean("commonExcelParse");//设置头信息
            List<SwTkStockFlow> list = excelParser.parse(sheet, new SwTkStockFlow());
            swTkStockFlowService.saveBatch(list);
            return R.ok("1", "导入成功");
        } catch (Exception e) {
            log.error("", e);
            return R.failed("Excel导入失败！");
        }
    }

    @ApiOperation(value = "导出库内流动信息", notes = "导出库内流动信息")
    @GetMapping("/export")
    @SysLog("导出库内流动信息")
    public void exportExcel(SwTkStockFlow swTkStockFlow, HttpServletResponse response) throws IOException {
        List<SwTkStockFlow> swTkStockFlowList = swTkStockFlowService.list(Wrappers.query(swTkStockFlow));
        String fileName = URLEncoder.encode("库内流动", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwTkStockFlow.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("库内流动").doWrite(swTkStockFlowList);
    }

}
